<template>
  <div style="margin: 10px 10px 0 10px;">
    <el-row :gutter="10">
      <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span>消息发布</span>
          </div>
          <div>
            <el-form ref="form" :model="form">
              <el-form-item label="客户端ID">
                <el-input v-model="form.clientId" />
              </el-form-item>
              <el-form-item label="主题">
                <el-input v-model="form.topic" />
              </el-form-item>
              <el-form-item label="消息">
                <el-input v-model="form.msg" />
              </el-form-item>
              <el-form-item label="服务质量">
                <el-select v-model="form.qos" placeholder="请选择服务质量" style="width:100%">
                  <el-option label="最多一次，有可能重复或丢失" value="0" />
                  <el-option label="至少一次，有可能重复" value="1" />
                  <el-option label="只有一次，确保消息只到达一次" value="2" />
                </el-select>
              </el-form-item>
              <el-button round type="success" style="width:100%;" @click="sendMessage">
                立即发送
              </el-button>
            </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span>消息订阅</span>
          </div>
          <div>
            <el-form ref="form" :model="subForm">
              <el-form-item label="客户端ID">
                <el-input v-model="subForm.clientId" />
              </el-form-item>
              <el-form-item label="订阅主题">
                <el-input v-model="subForm.topic" />
              </el-form-item>
              <el-button round type="primary" style="width:100%;" @click="subMessage">
                订阅消息
              </el-button>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px;">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <!-- 消息接收表格 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span>消息订阅后接收区域</span>
          </div>
          <div>
            <el-table
              :data="tableData"
              style="width: 100%"
            >
              <el-table-column
                prop="topic"
                label="主题"
              />
              <el-table-column
                prop="msg"
                label="消息"
              />
              <el-table-column
                prop="date"
                label="日期"
              />
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { subTopic, sendMessage } from '@/api/mqtt'

export default {
  name: 'Mqtt',
  components: {},
  data() {
    return {
      visible: false,
      // 发送变量
      form: {
        clientId: 'pushClient_001',
        topic: 'topic/1',
        msg: '{ "msg": "Hello, World!" }',
        qos: []
      },
      // 消息订阅变量
      subForm: {
        clientId: 'subClient_001',
        topic: 'topic/#'
      },
      tableData:
        [
          /*
          {
            date: '2016-05-02',
            topic: 'topic/#',
            msg: '{ "msg": "Hello, World!" }'
          }
          */
        ]
    }
  },
  watch: {
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    // 连接webSocket，用于接收后台实时信息推送
    this.initWebSocket()
    // 消息发送
    this.threadPoxi()
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    // 主题发布
    sendMessage() {
      const params = {
        'clientId': this.form.clientId,
        'topic': this.form.topic,
        'msg': this.form.msg,
        'qos': this.form.qos
      }
      sendMessage(params).then(res => {
        console.log(res)
        this.$message({
          message: '主题发布成功',
          type: 'success'
        })
      })
    },
    // 消息订阅
    subMessage() {
      const params = {
        'clientId': this.subForm.clientId,
        'topicName': this.subForm.topic
      }
      subTopic(params).then(res => {
        console.log(res)
        this.$message({
          message: '消息订阅成功',
          type: 'success'
        })
      })
    },
    // 实际调用的方法
    threadPoxi() {
      // 参数
      const agentData = 'mymessage'
      const that = this
      // 若是ws开启状态
      if (this.websock.readyState === this.websock.OPEN) {
        this.websocketSend(agentData)

        // 若是 正在开启状态，则等待300毫秒
      } else if (this.websock.readyState === this.websock.CONNECTING) {
        // 保存当前对象this
        setTimeout(function() {
          that.websocketSend(agentData)
        }, 300)

        // 若未开启 ，则等待500毫秒
      } else {
        this.initWebSocket()
        // 保存当前对象this
        setTimeout(function() {
          that.websocketSend(agentData)
        }, 500)
      }
    },
    // 初始化weosocket
    initWebSocket() {
      // ws地址
      // const wsUri = process.env.WS_API + '/websocket/123'
      // const wsUri = 'ws://132.232.131.152:7733/mqtt/websocket/123'

      const wsUri = 'ws://132.232.131.152:7733/websocket/123'
      this.websock = new WebSocket(wsUri)
      this.websock.onmessage = this.websocketOnMessage
      this.websock.onclose = this.websocketClose
    },
    // 数据接收
    websocketOnMessage(e) {
      console.log(e)
      this.tableData.push(JSON.parse(e.data))
      // this.tableData = e.data
      // const redata = JSON.parse(e.data)
      // console.log(redata)
    },
    // 数据发送
    websocketSend(agentData) {
      this.websock.send(agentData)
    },
    // 关闭
    websocketClose(e) {
      console.log('connection closed (' + e.code + ')')
    }
  }
}
</script>

<style scoped>
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
</style>
